package cn.itcast.dao.impl;

import cn.itcast.dao.StudentDao;
import cn.itcast.datasource.MyDataSource;
import cn.itcast.domain.Student;
import cn.itcast.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;
    private MyDataSource dataSource = null;
    @Override
    public List<Student> findAll() {
        List<Student> lis = new ArrayList<Student>();


        try {
            //创建数据库连接池对象
            MyDataSource dataSource = new MyDataSource();
            System.out.println("使用前连接数量" +dataSource.getSize());
            //定义sql
            String sql = "select * from student";

            //获取数据库连接对象
             conn = dataSource.getConnection();
            //执行sql 获取结果集
            ResultSet rs = ps.executeQuery();

            //遍历结果集,将数据封装到Student对象中,然后添加到集合里
            while (rs.next()) {
                Student stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getDate(4));
                lis.add(stu);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            JDBCUtil.close(null,ps,rs);

        }
        System.out.println("使用前连接数量" +dataSource.getSize());

        return lis;
    }
}
